<template>
  <div class="login-container">
    <div class="logo" />
    <div class="form">
      <h1>{{ qrCodeUrl && codeState === 1 ? "二维码登录" : "手机号登录" }}</h1>
      <el-card shadow="never" class="login-card">
        <div>
          <img
            v-if="qrCodeUrl && codeState === 1"
            :src="qrCodeUrl"
            alt="二维码"
            class="code-picture"
          />
          <div v-if="qrCodeUrl && codeState === 2" class="status-text">
            用户已扫码
          </div>
          <div v-if="qrCodeUrl && codeState === 4" class="status-text">
            二维码已失效
          </div>
          <div v-if="qrCodeUrl && codeState === 5" class="status-text">
            用户已取消，请重新扫码
          </div>
          <!-- 隐藏表单，当二维码可用时 -->
          <el-form
            v-if="
              !(
                qrCodeUrl &&
                (codeState === 1 ||
                  codeState === 2 ||
                  codeState === 4 ||
                  codeState === 5)
              )
            "
            ref="form"
            :model="loginForm"
            :rules="loginRules"
          >
            <el-form-item prop="mobile">
              <el-input placeholder="请输入手机号" v-model="loginForm.mobile" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                type="password"
                placeholder="请输入密码"
                v-model="loginForm.password"
              />
            </el-form-item>
            <el-form-item prop="isAgree">
              <el-checkbox v-model="loginForm.isAgree">
                用户平台使用协议
              </el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button style="width: 350px" type="primary" @click="login"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <el-button style="width: 170px" @click="resetQRCode"
          >手机号登入</el-button
        >
        <el-button style="width: 170px" @click="scancodeLogin">{{
          codeState === 4 || codeState === 5 ? "请重新获取二维码" : "扫码登入"
        }}</el-button>
      </el-card>
    </div>
  </div>
</template>
<script>
import { getLoginQrCode, getLoginQrCodeStatus } from "@/api/user";
import { generateQRCode } from "@/utils";
export default {
  name: "Login",
  data() {
    return {
      codeState: 0, // 二维码状态
      qrCodeUrl: "", // 存储二维码的 URL
      loginForm: {
        mobile: process.env.NODE_ENV === "development" ? "13800000002" : "",
        password: process.env.NODE_ENV === "development" ? "hm#qd@23!" : "",
        isAgree: process.env.NODE_ENV === "development",
      },
      loginRules: {
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 16,
            message: "密码长度应该为6-16位之间",
            trigger: "blur",
          },
        ],
        // required只能检查 null "" undefined
        isAgree: [
          {
            validator: (rule, value, callback) => {
              // rule规则
              // value检查的数据 true/false
              // callback 函数 执行这个函数
              // 成功执行callback 失败也执行callback(错误对象 new Error(错误信息))
              value ? callback() : callback(new Error("没有勾选用户平台协议"));
            },
          },
        ],
      },
      qrCodeCheckInterval: null, // 存储定时器
      codeState: 0, // 二维码状态
    };
  },
  methods: {
    // 手机号登录
    login() {
      this.$refs.form.validate(async (isOK) => {
        if (isOK) {
          await this.$store.dispatch("user/login", this.loginForm);
          // 提示登入成功
          this.$message.success("登录成功");
          // 跳转到主页
          this.$router.push("/");
        }
      });
    },
    // 生成二维码
    async scancodeLogin() {
      let res = await getLoginQrCode();
      this.qrCodeUrl = await generateQRCode(res);
      // console.log("加密串", res);
      this.startQRCodeStatusCheck(res); // 开始检查二维码状态
    },
    // 重置二维码
    resetQRCode() {
      this.qrCodeUrl = "";
      clearInterval(this.timer); // 清除定时器
    },
    // 检查二维码状态
    startQRCodeStatusCheck(res) {
      const checkStatus = async () => {
        const { codeState, token } = await getLoginQrCodeStatus(res);
        this.codeState = codeState; // 存储状态
        console.log("二维码状态", codeState, token);
        if (codeState === 4 || codeState === 5) {
          clearInterval(this.timer);
        } else if (codeState === 3) {
          // 清除定时器
          clearInterval(this.timer);
          // 提示登入成功
          this.$message.success("二维码已被扫描，正在登录...");
          // 跳转到主页;
          this.$store.commit("user/setToken", token);
          this.$router.push("/");
        }
      };
      // 每1秒执行一次
      this.timer = setInterval(() => {
        checkStatus();
      }, 1000);
    },
  },
  // 组件销毁时清除定时器
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>
<style lang="scss">
.status-text {
  // text-align: center;
  margin-top: 50px;
  margin-bottom: 50px;
  color: #909399;
}
.code-picture {
  width: 300px;
  height: 300px;
}
.login-container {
  display: flex;
  align-items: stretch;
  height: 100vh;
  .logo {
    flex: 3;
    background: rgba(38, 72, 176) url(../../assets/common/login_back.png)
      no-repeat center / cover;
    border-top-right-radius: 60px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    padding: 0 100px;
    .icon {
      background: url(../../assets/common/logo.png) no-repeat 70px center /
        contain;
      width: 300px;
      height: 50px;
      margin-bottom: 50px;
    }
    p {
      color: #fff;
      font-size: 18px;
      margin-top: 20px;
      width: 300px;
      text-align: center;
    }
  }
  .form {
    flex: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 176px;
    .el-card {
      border: none;
      padding: 0;
    }
    h1 {
      padding-left: 20px;
      font-size: 24px;
    }
    .el-input {
      width: 350px;
      height: 44px;
      .el-input__inner {
        background: #f4f5fb;
      }
    }
    .el-checkbox {
      color: #606266;
    }
  }
}
</style>
